#! /usr/bin/env python3
# coding = utf-8

# Definition for singly-linked list.


class ListNode(object):
    def __init__(self, x):
        self.val = x
        self.next = None


def print_list(head):
    n = head
    while n is not None:
        print(n.val, end=" ")
        n = n.next
    print()


class Solution(object):
    def swapPairs(self, head):
        if head is None or head.next is None:
            return head

        p, q = head, head.next

        new_head = ListNode(None)
        new_tail = new_head
        while True:
            next = q.next
            q.next = p
            p.next = None
            new_tail.next = q
            new_tail = p
            if None is next or None is next.next:
                break
            p, q = next, next.next
        if next:
            new_tail.next = next
        return new_head.next

head = ListNode(None)
test = [1, 2, 3, 4, 5, 6, 7]
prev = head
for i in test:
    node = ListNode(i)
    prev.next = node
    prev = node


s = Solution()
h = s.swapPairs(head.next)
print_list(h)
